import useRequest from "./useRequest";

type UseUpload = {
  onSuccess?: (url: string) => void;
};

export default (options?: UseUpload) => {
  /**
     * v  action: "/web/v1/tools/upload",
  fileSize: 1024 * 10,
  compress: true,
  limit: 1,
  cardSize: ".el-upload-list--picture-card",
     */
  const { isFetching, data, run, onFetchResponse } = useRequest(
    "/web/v1/tools/upload",
    { immediate: false }
  );

  onFetchResponse(() => {
    options?.onSuccess?.(data.value);
  });

  const chooseMedia = () => {
    var fileInput = document.createElement("input");
    fileInput.setAttribute("type", "file");
    fileInput.setAttribute("accept", "image/*");
    fileInput.click();

    fileInput.onchange = function () {
      var file = fileInput.files?.[0];

      if (file) {
        var formData = new FormData();
        formData.append("file", file);
        run(formData);
      }
    };
  };

  return {
    isFetching,
    data,

    
    chooseMedia,
  };
};
